package com.spodrum.balloon;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;

class ParticleManager 
{

	private static int MAX_PARTICLES = 100;
	
	private ArrayList<Particle> mParticleList =new ArrayList<Particle>();
	private ArrayList<Particle> mRecycleList =new ArrayList<Particle>();

	private int mCanvasWidth;
	private int mCanvasHeight;
	private Paint mPaint;
	private Drawable mImage[] =new Drawable[3];

	public ParticleManager(Context mContext) 
	{
		this.mPaint = new Paint();
		mPaint.setColor(Color.WHITE);
		mImage[0] = mContext.getResources().getDrawable(R.drawable.spark1);
		mImage[1] = mContext.getResources().getDrawable(R.drawable.spark2);
		mImage[2] = mContext.getResources().getDrawable(R.drawable.spark3);

		//init max particles for use.
		for (int i = 0; i < MAX_PARTICLES; i++) 
			mRecycleList.add(new Particle(0, 0));
	}
	
	public void doDraw(Canvas c) 
	{
		for (int i = 0; i < mParticleList.size(); i++) 
		{
			Particle p = mParticleList.get(i);
			p.move();
			mImage[p.image].setColorFilter(p.getColour(), Mode.MULTIPLY);
			mImage[p.image].setAlpha(p.alpha);
			mImage[p.image].setBounds(p.x-10, 
										p.y-10, 
											p.x-10 + mImage[p.image].getIntrinsicWidth() , 
												p.y-10 + mImage[p.image].getIntrinsicHeight() );
			
			//c.drawBitmap(mImage[p.image], p.x-10, p.y-10, mPaint);
			mImage[p.image].draw(c);
			
			if (!p.isAlive() || p.x < 0 || p.x > mCanvasWidth || p.y < 0 || p.y > mCanvasHeight) 
			{
				mRecycleList.add(mParticleList.remove(i));
				i--;
			}
		}
	}
	
	public void spawnParticleExplosion(int x, int y, int colour)
	{
		Particle p;
		int recycleCount = mRecycleList.size();
		
		//Take 5 particles from the recycle list and initialise
		if(recycleCount >= 5)
		{
			for (int i = 0; i < 6; i++) 
			{
				p = mRecycleList.remove(i);
				p.init(x, y);
				p.setColour(colour);
				p.setAlive(true);
				mParticleList.add(p);
			}
		}
		
		/*
		Particle p;
		int recycleCount = 0;
		
		if(mRecycleList.size()>1)
			recycleCount = 2;
		else
			recycleCount =mRecycleList.size();
		
		for (int i = 0; i < recycleCount; i++) 
		{
			p = mRecycleList.remove(0);
			p.init(x, y);
			mParticleList.add(p);
		}

		for (int i = 0; i < 2-recycleCount; i++) 
			mParticleList.add(new Particle(x, y));
		
		*/
	}
		
	public ArrayList<Particle> getParticleList() {
		return mParticleList;
	}

	public ArrayList<Particle> getRecycleList() {
		return mRecycleList;
	}
	
	public void setSurfaceSize(int width, int height) {
		mCanvasWidth = width;
		mCanvasHeight = height;
	}

}